package com.file.tool.utils.pdf;

import cn.hutool.core.util.ObjectUtil;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class PDFUtil {

    // 凭证
    private static final String license =
            "<License>\n" +
                    "  <Data>\n" +
                    "    <Products>\n" +
                    "      <Product>Aspose.Total for Java</Product>\n" +
                    "      <Product>Aspose.Words for Java</Product>\n" +
                    "    </Products>\n" +
                    "    <EditionType>Enterprise</EditionType>\n" +
                    "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                    "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
                    "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                    "  </Data>\n" +
                    "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                    "</License>";

    /**
     * 验证License 若不验证则转化出的pdf文档会有水印产生
     *
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
//            InputStream is = this.getClass().getClassLoader().getResourceAsStream("license.xml");
            InputStream is = new ByteArrayInputStream(license.getBytes(StandardCharsets.UTF_8));
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * word转pdf
     *
     * @param inpath  word的全路径
     * @param outpath 输出pdf的路径
     * @return
     * @throws Exception
     */
    public static String word2Pdf2(String inpath, String outpath) throws Exception {
        return word2Pdf2(inpath, outpath, System.currentTimeMillis() + "");
    }


    /**
     * word转pdf
     *
     * @param worldFilePath word的全路径
     * @param outPdfPath    输出pdf的路径
     * @param outPdfName    输出pdf的名称
     * @return 返回pdf文件全路径
     * @throws Exception
     */
    public static String word2Pdf2(String worldFilePath, String outPdfPath, String outPdfName) throws Exception {
        File fileTemp = new File(worldFilePath);
        // 判断模板文件夹是否 不存在则创建
        if (!fileTemp.getParentFile().exists()) {
            fileTemp.getParentFile().mkdirs();
        }
        // 判断模板是否存在
        if (!fileTemp.exists()) {
            throw new RuntimeException("world文件不存在");
        }
        if (!getLicense()) {
            System.out.println("非法------------");
            return "";
        }
        long old = System.currentTimeMillis();
        if (ObjectUtil.isEmpty(outPdfName)) {
            outPdfName = old + "";
        }
        String outPdfFullPath = outPdfPath + outPdfName + ".pdf";
        File file = new File(outPdfFullPath);
        FileOutputStream os = new FileOutputStream(file);
        //解决乱码
        //如果是windows执行，不需要加这个
        //TODO 如果是linux执行，需要添加这个*****
        //FontSettings.setFontsFolder("/usr/share/fonts",true);
        Document doc = new Document(worldFilePath);
        //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
        doc.save(os, SaveFormat.PDF);
        long now = System.currentTimeMillis();
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒 >>>>>>>>>>" + outPdfFullPath);
        return outPdfFullPath;
    }

    /**
     * word转pdf
     *
     * @param wordFileInput world文件流
     * @param outPdfPath    输出pdf的路径
     * @param outPdfName    输出pdf的名称
     * @return 返回pdf文件全路径
     * @throws FileNotFoundException
     */
    public static String word2pdf(InputStream wordFileInput, String outPdfPath, String outPdfName) throws FileNotFoundException {
        if (wordFileInput == null) {
            throw new RuntimeException("world文件不存在");
        }
        if (!getLicense()) {
            System.out.println("非法");
            return "";
        }
        //新建一个空白pdf文档
        long old = System.currentTimeMillis();
        String outPdfFullPath = outPdfPath + outPdfName + ".pdf";
        File file = new File(outPdfFullPath);
        FileOutputStream os = new FileOutputStream(file);
        //Address是将要被转化的word文档
        Document doc = null;
        try {
            doc = new Document(wordFileInput);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long now = System.currentTimeMillis();
        //转化用时
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒>>>>>>>>>>" + outPdfFullPath);
        return outPdfFullPath;
    }


    /**
     * @return 返回pdf文件全路径
     * @throws FileNotFoundException
     */

    /**
     * word转pdf response直接下载
     *
     * @param wordFileInput world文件流
     * @param outPdfPath    输出pdf的路径
     * @param outPdfName    输出pdf的名称
     * @param response
     * @throws FileNotFoundException
     */
    public static void word2pdf(InputStream wordFileInput, String outPdfPath, String outPdfName, HttpServletResponse response) throws FileNotFoundException {
        if (wordFileInput == null) {
            throw new RuntimeException("world文件不存在");
        }
        if (!getLicense()) {
            System.out.println("非法");
            return;
        }
        //新建一个空白pdf文档
        long old = System.currentTimeMillis();
        //Address是将要被转化的word文档
        Document doc = null;
        try {
            //out为OutputStream，需要写出到的目标流
            //response为HttpServletResponse对象
            response.setContentType("application/pdf;charset=utf-8");
            //test.pdf 是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=" + outPdfName + ".pdf");
            ServletOutputStream out = response.getOutputStream();
            doc = new Document(wordFileInput);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(out, SaveFormat.PDF);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        long now = System.currentTimeMillis();
        //转化用时
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");
    }

    public static void main(String[] args) throws Exception {
        String filePaths = "E:\\my_work\\file-tool\\src\\main\\java\\com\\file\\tool\\utils\\world\\temp\\1675670203165.docx";
        String pdfPath = "E:\\my_work\\file-tool\\src\\main\\java\\com\\file\\tool\\utils\\world\\temp\\";
        PDFUtil.word2Pdf2(filePaths, pdfPath);
    }


}
